package org.fuys.coder.infrastructure.scheduled;

import org.fuys.coder.common.constants.RedisConstants;
import org.fuys.coder.common.holder.CategoryVOHolder;
import org.fuys.coder.infrastructure.util.RedisUtil;
import org.fuys.coder.domain.category.model.vo.CategoryVO;
import org.fuys.coder.domain.substance.model.vo.SubstanceVO;
import org.fuys.coder.domain.substance.service.repo.ISubstanceService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.infrastructure.scheduled
 * @className: PreLoadRecommendSubstance
 * @author: WangJing
 * @description: 预加载推荐内容
 * @date: 2024/9/3 21:57
 * @version: 1.0
 */
@Component
public class PreLoadRecommendSubstance {

    @Resource
    private ISubstanceService substanceService;

    @Resource
    private RedisUtil redisUtil;

    @Scheduled(cron = "0 0 0 */1 * ?")
    public void preLoad(){
        final List<Integer> collect = CategoryVOHolder.getAll().stream().map(CategoryVO::getId).collect(Collectors.toList());
        final List<SubstanceVO> substanceByCategories = substanceService.getSubstanceByCategories(collect, 1, 100);
        Map<Integer,List<SubstanceVO>> cacheMap=new HashMap<>();
        substanceByCategories.forEach(item->{
            final Integer categoryId = item.getCategoryId();
            final List<SubstanceVO> substanceVOS = cacheMap.get(categoryId);
            if(ObjectUtils.isEmpty(substanceVOS)){
                List<SubstanceVO> cacheList=new ArrayList<>();
                cacheList.add(item);
                cacheMap.put(categoryId,cacheList);
            }else{
                substanceVOS.add(item);
            }
        });
        String redisKeyPre= RedisConstants.REDIS_FIELD_SUBSTANCE+RedisConstants.REDIS_DESC_PRELOAD+":";

        cacheMap.forEach((key,value)->{
           String redisKey=redisKeyPre+key;
           redisUtil.deleteKey(redisKey);
           redisUtil.getRedisTemplate().opsForSet().add(redisKey,value.toArray());
        });
    }
}
